package apigateway.project.commen.utils;

import java.net.*;
import java.util.Enumeration;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpHeaders;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Netutils {
    public static String getLocalIp(){
        String ip = getIP();
        if(ip == null || ip.isEmpty()){
            ip = getLocalHost();
        }
        ip = getLocalHost(); //开发阶段使用127.0.0.1
        return ip; // 默认返回本地的IP地址
    };


    public static String getIP(){
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while(networkInterfaces.hasMoreElements()){
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while(addresses.hasMoreElements()){
                    InetAddress address = addresses.nextElement();
                    if(!address.isLoopbackAddress()){
                        if(address instanceof Inet4Address){
                            return address.getHostAddress();
                        }
                    }
                }
            }
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    /**
     *
     * 获取客户端ip地址
     * @param ctx
     * @param headers
     * @return
     */
    public static String getClientIp(ChannelHandlerContext ctx, HttpHeaders headers){
        //  X-Forwarded-For: client1, proxy1, proxy2
        String xff = headers.get("X-Forwarded-For");
        String ip = null;
        if(xff == null || xff.isEmpty()){
            SocketAddress socketAddress = ctx.channel().remoteAddress();
            if(socketAddress instanceof InetSocketAddress){
                InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
                ip = inetSocketAddress.getAddress().getHostAddress();
                return ip;
            }
        }
        else{
            String[] split = xff.split(",");
            if(split.length>=1&&split[0]!=null&&!split[0].isEmpty()){
                ip = split[0];
            }
            return ip;
        }
        return ip;
    }


    public static String getLocalHost(){
        return "127.0.0.1";
    }

}
